# sniffing_tool.py

from scapy.all import sniff, Ether, IP, TCP, UDP, DNS, HTTPRequest
from collections import Counter
import json
import sys

# 数据包计数器
packet_counts = Counter()

def packet_callback(packet):
    # 以太网层
    if packet.haslayer(Ether):
        ether_layer = packet[Ether]
        packet_counts["Ethernet"] += 1
        print(f"Ethernet Frame: {ether_layer.src} -> {ether_layer.dst}")

    # IP层
    if packet.haslayer(IP):
        ip_layer = packet[IP]
        packet_counts["IP"] += 1
        print(f"IP Packet: {ip_layer.src} -> {ip_layer.dst}")

    # TCP层
    if packet.haslayer(TCP):
        tcp_layer = packet[TCP]
        packet_counts["TCP"] += 1
        print(f"TCP Segment: {ip_layer.src}:{tcp_layer.sport} -> {ip_layer.dst}:{tcp_layer.dport}")
        
        # HTTP请求
        if packet.haslayer(HTTPRequest):
            http_layer = packet[HTTPRequest]
            packet_counts["HTTP"] += 1
            print(f"HTTP Request: {http_layer.Host.decode()} {http_layer.Path.decode()}")

    # UDP层
    if packet.haslayer(UDP):
        udp_layer = packet[UDP]
        packet_counts["UDP"] += 1
        print(f"UDP Datagram: {ip_layer.src}:{udp_layer.sport} -> {ip_layer.dst}:{udp_layer.dport}")
        
        # DNS请求
        if packet.haslayer(DNS) and packet[DNS].qr == 0:
            dns_layer = packet[DNS]
            packet_counts["DNS"] += 1
            print(f"DNS Request: {dns_layer.qd.qname.decode()}")

def generate_report():
    """生成流量统计报告"""
    report = {
        "total_packets": sum(packet_counts.values()),
        "details": packet_counts
    }
    with open("traffic_report.json", "w") as f:
        json.dump(report, f, indent=4)
    print("\nTraffic report generated: traffic_report.json")

def main(interface):
    print(f"Sniffing on interface {interface}...")
    try:
        sniff(iface=interface, prn=packet_callback, store=0)
    except KeyboardInterrupt:
        print("\nStopping sniffing...")
        generate_report()

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 sniffing_tool.py <interface>")
        sys.exit(1)

    interface = sys.argv[1]
    main(interface)
# pip install scapy
# sansjtw